package cn.ichiva.puppet.example.base.p2;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLPath;
import javafx.fxml.InvokeAbleMethod;
import javafx.fxml.impl.AbstractPuppetComponent;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class TodoList extends AbstractPuppetComponent {

    @Override
    public CharSequence render() {
        imports(VBox.class, HBox.class, TextField.class, Button.class, CheckBox.class);

        return """
                <VBox>
                   <HBox for="index : todoList">
                        <TextField text="${controller.todoList.get(index)}" />
                        <Button text="x" onAction="${controller.removeTodo(index)}"  />
                    </HBox>
                </VBox>
                """;
    }

    @FXML
    public List<StringProperty> todoList;

    private InvokeAbleMethod parentRemoveTodo;

    @FXML
    public void removeTodo(int index) throws InvocationTargetException, IllegalAccessException {
        parentRemoveTodo.invoke(index);
    }

    @Override
    public void setProps(Map<String, Object> props) {
        this.todoList = ((List<Todo>) props.get("list")).stream().map(e -> new SimpleStringProperty(e.getText())).collect(Collectors.toList());
        this.parentRemoveTodo = (InvokeAbleMethod) props.get("#removeTodo");
    }
}
